<template>
  <div class="sales-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>销售仪表板</h1>
      <p>实时监控销售业绩和订单状态</p>
    </div>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalOrders }}</div>
              <div class="stat-label">订单总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon warning">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.pendingOrders }}</div>
              <div class="stat-label">待处理订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon success">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.completedOrders }}</div>
              <div class="stat-label">已完成订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon info">
              <el-icon><InfoFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.problemOrders }}</div>
              <div class="stat-label">问题订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 业绩概览 -->
    <el-row :gutter="20" class="overview-section">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>近期订单</span>
              <el-button link @click="viewAllOrders">
                查看全部 <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </template>
          
          <el-table 
            :data="recentOrders" 
            v-loading="loading"
            style="width: 100%"
          >
            <el-table-column prop="platformOrderId" label="订单号" />
            <el-table-column prop="customerId" label="客户ID" />
            <el-table-column prop="orderAmount" label="订单金额">
              <template #default="{ row }">
                ¥{{ row.orderAmount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="orderStatus" label="订单状态" />
            <el-table-column prop="invoiceStatus" label="开票状态" />
            <el-table-column prop="orderDate" label="下单时间" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button link @click="viewOrderDetail(row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.limit"
              :total="pagination.total"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>智能提醒</span>
          </template>
          
          <div class="alerts-container">
            <div 
              v-for="alert in smartAlerts" 
              :key="alert.id" 
              class="alert-item"
              :class="alert.severity"
              @click="handleAlertClick(alert)"
            >
              <div class="alert-icon">
                <el-icon v-if="alert.type === 'duplicateInvoice'"><Warning /></el-icon>
                <el-icon v-else><InfoFilled /></el-icon>
              </div>
              <div class="alert-content">
                <div class="alert-title">{{ alert.title }}</div>
                <div class="alert-description">{{ alert.content }}</div>
              </div>
              <div class="alert-count">{{ alert.count }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  TrendCharts, 
  User, 
  Warning, 
  InfoFilled,
  ArrowRight
} from '@element-plus/icons-vue'

// 导入API
import { getSalesOrders, getSalesOrderStats } from '@/api/sales'

// 数据模型
interface SalesStats {
  totalOrders: number
  pendingOrders: number
  completedOrders: number
  problemOrders: number
  monthlyAmount: number
  avgOrderAmount: number
  completionRate: number
  uninvoicedOrders: number
  amountTrend: number
  avgTrend: number
  completionTrend: number
  invoiceTrend: number
}

interface SalesOrder {
  id: number
  platformOrderId: string
  customerId: number
  orderAmount: number
  orderDate: string
  invoiceStatus: string
  invoiceDate: string
  invoiceNumber: string
  orderStatus: string
  createdAt: string
  updatedAt: string
}

interface SmartAlert {
  id: number
  type: 'duplicateInvoice' | 'largeAmount'
  title: string
  content: string
  severity: 'warning' | 'info'
  count: number
}

interface Pagination {
  page: number
  limit: number
  total: number
}

// 响应式数据
const router = useRouter()
const stats = ref<SalesStats>({
  totalOrders: 0,
  pendingOrders: 0,
  completedOrders: 0,
  problemOrders: 0,
  monthlyAmount: 0,
  avgOrderAmount: 0,
  completionRate: 0,
  uninvoicedOrders: 0,
  amountTrend: 0,
  avgTrend: 0,
  completionTrend: 0,
  invoiceTrend: 0
})

const recentOrders = ref<SalesOrder[]>([])
const smartAlerts = ref<SmartAlert[]>([
  {
    id: 1,
    type: 'duplicateInvoice',
    title: '重复开票提醒',
    content: '检测到3个订单存在重复开票风险',
    severity: 'warning',
    count: 3
  },
  {
    id: 2,
    type: 'largeAmount',
    title: '大额订单提醒',
    content: '今日新增2个超过10万元的大额订单',
    severity: 'info',
    count: 2
  }
])

const loading = ref(false)
const pagination = ref<Pagination>({
  page: 1,
  limit: 5,
  total: 0
})

// 方法
const loadStats = async () => {
  try {
    const response = await getSalesOrderStats()
    stats.value = response
  } catch (error) {
    ElMessage.error('获取销售统计数据失败: ' + (error as Error).message)
  }
}

const loadRecentOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      limit: pagination.value.limit
    }
    
    const response = await getSalesOrders(params)
    
    recentOrders.value = response.list
    pagination.value.total = response.pagination.total
  } catch (error) {
    ElMessage.error('获取销售订单列表失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const handleAlertClick = (alert: any) => {
  ElMessage.info(`处理提醒: ${alert.title}`)
  // 可以根据提醒类型执行不同的操作
}

const viewAllOrders = () => {
  router.push('/sales/orders')
}

const viewOrderDetail = (order: SalesOrder) => {
  ElMessage.info(`查看订单详情: ${order.platformOrderId}`)
}

const handleSizeChange = (size: number) => {
  pagination.value.limit = size
  loadRecentOrders()
}

const handleCurrentChange = (page: number) => {
  pagination.value.page = page
  loadRecentOrders()
}

// 生命周期
onMounted(() => {
  loadStats()
  loadRecentOrders()
})
</script>